﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
Axis.Admin.Member = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        var cdropdown = new CDropDownCheckList({ width: 200 });
        cdropdown.Init("#ddlFilter");
        var cdropdown2 = new CDropDownCheckList({ width: 200, maxDropHeight: 110, firstItemChecksAll: true });
        cdropdown2.Init("[id$='ddlProvinceFilter'],[id$='ddlEducationFilter'],[id$='ddlClassFilter'],[id$='ddlMaritalStatusFilter'],[id$='ddlEducationFilter'],[id$='ddlJobFilter'],[id$='ddlTypeFilter'],[id$='ddlGenderFilter']");
        $("#FormFilter").hide();
        thisObj.Click();
    },
    ConfirmUpdateVerified:function(rowData){    
   var  thisObj=this;
      $.CAlert.Confirm({
                    Title: "Active account",
                    Content: $.string.Format("Bạn có chắc muốn active tài khoản: {0}.", rowData.Email)
                }, function (isOK) {
                    if (isOK)
                        thisObj.UpdateVerified( rowData);
                });
    },
    UpdateVerified:function(rowData){
        var  data={ID:rowData.ID,Email:$("#VerifiedMember_Email").val(),IsReset:$("#VerifiedMember_Email").is(':checked'),Action:"EmailAndActive",Active:1};
        $.Ajax({
            url: 'Service/MemberService2.asmx/VerifyMenber',
            type: 'POST',
           contentType: "application/json; charset=utf-8",
            dataType: "json",
            data:JSON.stringify(data) ,
            success: function (pData, textStatus, jqXHR) {            
            var data=pData.d;
                if (data) {                                  
                    if (data.IsSuccessfull) {
                        Axis.Admin.Member.Grid.Reload();
                         Axis.Admin.Member.DialogVerified.Dialog.Close();
                    }
                    else
                     $.CAlert.Alert({
                    Title: data.Name,
                    Content: data.Description
                    });
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        Instance: null,
        Init: function () {
            var thisObj = this;
            var options = {
                url: 'Service/MemberService.ashx?Action=GET',
                datatype: "json",
                sortname: "ID",
                sortorder: "desc",                
                colNames: [
                    'ID', 'First Name', 'Last Name', 'Email', 'Type', 'Type', 'Mức Lương', 'Class',
                    'Trình Độ', 'EducationID',
                    'Hôn Nhân', 'MaritalStatus',
                    'Điểm', 'CMND', '', 'ĐT Di Động', 'ĐT Cố Định', 'Ngày Sinh',
                    'Giới Tính', 'Gender', 'Nghề Nghiệp', 'JobID',
                    'Địa Chỉ', 'Quận', 'Tỉnh Thành', 'ProvinceID', 'Xác Nhận','','Quà tặng'//,'Xử lý'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, hidden: true, frozen: true, hidedlg: true },
                    { name: 'FirstName', index: 'FirstName', width: 90, frozen: true },
                    { name: 'LastName', index: 'LastName', width: 60, frozen: true },
                    { name: 'Email', index: 'Email', width: 190, align: 'center',editable:true},
                    { name: 'TypeName', index: 'TypeName', width: 50, align: 'center', hidden: true, hidedlg: true },
                    { name: 'Type', index: 'Type', hidden: true, hidedlg: true },
                    { name: 'ClassName', index: 'ClassName', width: 70, align: 'center' },
                    { name: 'Class', index: 'Class', hidden: true, hidedlg: true },
                    { name: 'EducationName', index: 'EducationName', width: 70 },
                    { name: 'EducationID', index: 'EducationID', hidden: true, hidedlg: true },
                    { name: 'MaritalStatusName', index: 'MaritalStatusName', width: 70, align: 'center' },
                    { name: 'MaritalStatus', index: 'MaritalStatus', hidden: true, hidedlg: true },
                    { name: 'Mark', index: 'Mark', width: 35, align: 'center' },
                    { name: 'CMND', index: 'CMND', width: 70, align: 'center' },
                    { name: 'Email2', index: 'Email', width: 1, align: 'center', hidden: true },
                    { name: 'Mobile', index: 'Mobile', width: 70, align: 'center', hidden: true },
                    { name: 'Phone', index: 'Phone', width: 70, align: 'center', hidden: true },
                    {
                        name: 'DateOfBirth', index: 'DateOfBirth', width: 70, align: 'center', formatter: 'date', formatoptions: {
                            srcformat: "m/d/Y",
                            newformat: "d/m/Y"
                        }
                    },
                    { name: 'GenderName', index: 'GenderName', width: 50, align: 'center' },
                    { name: 'Gender', index: 'Gender', hidden: true, hidedlg: true },
                    { name: 'JobName', index: 'JobName', width: 100, align: 'center' },
                    { name: 'JobID', index: 'JobID', hidden: true, hidedlg: true },
                    { name: 'Address', index: 'Address', width: 170, hidden: true },
                    { name: 'Ward', index: 'Ward', width: 50, align: 'center', hidden: true },
                    { name: 'ProvinceName', index: 'ProvinceName', width: 90 },
                    { name: 'ProvinceID', index: 'ProvinceID', hidden: true, hidedlg: true },
                    { name: 'IsVerifiedString', index: 'Status', width: 60, align: 'center' },
                    { name: 'IsVerified', index: 'Status', width: 160, align: 'center',hidden: true  },
                    { name: 'Gift', index: 'Status', width: 60, align: 'center' }
                   // ,{ name: 'Action', index: 'Action', width: 55, align: 'center' }
                ],
                afterEditCell: function (rowid, cellname, val, iRow, iCol) {
           
                var rowData = $("#GridContents").jqGrid('getRowData', rowid);
                if (rowData.IsVerified != "0")
                    $("#GridContents").restoreCell(iRow, iCol);
                
                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {
                },
                onSelectRow: function (rowid, status, e) {
                },
                ondblClickRow: function (rowid, iRow, iCol, e) {
                },
                afterInsertRow: function (rowid, rowdata, rowelem) {
                    var thisObj=this;
                    var actionHtml = $.string.Format('<img src="{1}" class="imgAction"  rowID="{0}" id="Action{0}" loaded="0"/>', rowid, "../../Images/16x16/s_enable.png", "");
                    if(rowdata.IsVerified=='0')
                    actionHtml = $.string.Format('<img src="{1}"  class="imgAction"  rowID="{0}" id="ActionVerify{0}" loaded="0"/>', rowid, "../../Images/16x16/notActive.png", "");
                    $("#GridContents").setCell(rowid, 'IsVerifiedString', actionHtml);
                     if(rowdata.IsVerified=='0'){
                         $("#ActionVerify"+rowid).bind('click', function () {
                            Axis.Admin.Member.DialogVerified.Init(rowid);
                        });
                    }
                    var giftHtml = $.string.Format('<img src="{1}" class="imgAction"  rowID="{0}" id="ActionGift{0}" loaded="0"/>', rowid, "../../Images/16x16/present.png", "");
                     $("#GridContents").setCell(rowid, 'Gift', giftHtml);                    
                         $("#ActionGift"+rowid).bind('click', function () {
                            window.location.assign( $.string.Format("../Accounts/MemberGift.aspx?ID={0}", rowid));
                        });
                    
                },
                gridComplete: function () {
                    $('.imgMemberAvatar').tooltip({
                        delay: 0,
                        track: true,
                        showURL: false,
                        bodyHandler: function () {
                            return $("<img/>").attr("src", this.src);
                        }
                    });
                },
                loadComplete: function () {
                },
                //multiselect: true,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 20,
                pager: thisObj.PagesID,
                editurl: "Service/EditUser.ashx"
            };
            thisObj.Instance = new CGrid(options);
            thisObj.Instance.Init(thisObj.ID);
            thisObj.Instance.NavGrid();
            thisObj.Instance.FrozenColumns();
        },
        HideColumn: function (colName) {
            var thisObj = this;
            if (thisObj.Instance)
                return thisObj.Instance.HideColumn(colName);
        },
        ShowColumn: function (colName) {
            var thisObj = this;
            if (thisObj.Instance)
                return thisObj.Instance.ShowColumn(colName);
        },
        GetColumnModel: function () {
            var thisObj = this;
            if (thisObj.Instance)
                return thisObj.Instance.GetColumnModel();
            else
                return null
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.Instance)
                thisObj.Instance.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                return thisObj.Instance.SelectRow();
            }
            return null;
        },
        SelectArrRow: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                return thisObj.Instance.SelectArrRow();
            }
            return null;
        }
    },

    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    width: 380
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            Axis.Admin.Member.ClearForm();
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Add New User");
                    $("#FormEdit [data-role='INSERT']").show();
                    $("#FormEdit").find("#txtEmail").focus();
                    buttonText = "Add";
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Edit: " + opts.Email);
                    $.each(opts, function (key, value) {
                        $("#FormEdit [data-field=" + key + "]").val(value);
                    });
                    buttonText = "Update";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.Member.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    DialogVerified:{
     ID: "#VerifiedMember",
        Dialog: null,
        Init: function (rowID) {  
        console.log("#VerifiedMember",rowID);      
        var  opts=$("#GridContents").jqGrid('getRowData', rowID);
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Verified member : "+ opts.Email,
                    width: 350,
                    height: 200
                });  
                thisObj.Dialog.Init(thisObj.ID);         
            }

          
             thisObj.Dialog.SetTitle("Verified member : " + opts.Email);
            var buttons = [
                        {
                            text: "Update",
                            click: function (e) {
                               Axis.Admin.Member.ConfirmUpdateVerified(opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }
                        ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
              $("#VerifiedMember_Email").val(opts.Email);
        },
        Open: function () {
            var thisObj = this; 
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }        
       
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        ClearForm: function () {
       $("#VerifiedMember_Email").val('');
       $("VerifiedMember_Password").attr('checked','false');    
         }
    },
    
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (type, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Filter",
                    width: 330,
                    height: 400,
                    buttons: [
                        {
                            text: "Search",
                            click: function (e) {
                                var data = {};
                                $("#FormFilter").find("input,select").each(function () {
                                    var $this = $(this);
                                    if ($this.attr("data-field")) {
                                        var key = $this.attr("data-field");
                                        var value = $this.val();
                                        if ($.isArray(value)) {
                                            data[key] = value.join(", ");
                                        }
                                        else {
                                            data[key] = value;
                                        }
                                    }
                                });
                                data = decodeURIComponent($.param(data));
                                $("#GridContents").jqGrid('setGridParam', { url: "Service/MemberService.ashx?Action=GET" + data, page: 1 }).trigger("reloadGrid");
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

                    ]
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    ClearForm: function () {
        $("#FormEdit").find("[data-field]").each(function () {
            var $this = $(this);
            $this.val("");
            if ($this.is("select")) {
                var value = $this.find("option[Default-Value='1']").attr("value");
                $this.val(value);
            }

        });
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                    }
                });
                break;
            case "UPDATE":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    var value = $this.val();
                    if ($this.attr("data-field") && $this.attr("data-role") != "Password") {
                        var key = $this.attr("data-field");
                        if (key == "DateOfBirth") {
                            value = $.CFormat.FormatDate(value, "yyyy/MM/dd", "vi-VN", "en-US");
                        }
                        data[key] = value;
                    }
                });
                break;
            case "DELETE":
                data.ID = opts.ID;
                break;
        }
        data.Action = type;
        data.oper = type.toLowerCase();
        $.Ajax({
            url: 'Service/MemberService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        Axis.Admin.Member.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Click: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            $('div[data-role="Password"]').show();
            $('div[data-role="ResetPassword"]').hide();
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            $('div[data-role="Password"]').hide();
            $('div[data-role="ResetPassword"]').show();
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else {
                $.CAlert.Alert({
                    Title: "Sửa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần sửa."
                });
            }
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa tài khoản",
                    Content: $.string.Format("Bạn có chắc muốn xóa tài khoản: {0}.", rowData.Email),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần xóa."
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });

        $("#imgUserExport").bind('click', function () {
                   ExportExcel(0,0);
                });
    }
};
$(function () {
    Axis.Admin.Member.Init();
});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.Member;
    $('div[data-role="Password"]').hide();
    $('div[data-role="ResetPassword"]').show();
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}


function ExportExcel(ID,Completed){
    window.open('ExportExcel.aspx?ID='+ID+'&Type=0&Completed='+Completed);
}